package com.shop.admin.interceptors;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.shop.admin.result.ApiResult;
import com.shop.admin.utils.jwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JWTInterceptor implements HandlerInterceptor {
		public static String userId;

		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

				//如果是OPTIONS请求 直接放行
				String method = request.getMethod();
				if(method.equals("OPTIONS")){
						return  true;
				}

				String msg = "";
				//获取请求头中的令牌
				String token = request.getHeader("token");

				try {
					DecodedJWT verify = jwtUtils.verify(token);//验证令牌
					userId = verify.getClaim("id").asString();

					return  true;            // 放行请求

				}catch (SignatureVerificationException e){
             // e.printStackTrace();
						msg = "无效签名！" ;
				}catch (TokenExpiredException e){
						msg = "登录过期！" ;
				}catch (AlgorithmMismatchException e){
						msg = "token算法不一致！" ;
				}catch (Exception e){
						msg = "token无效！" ;
				}

        response.setContentType("application/json;charset=utf-8");
			ApiResult<Object> objectApiResult = new ApiResult<>(10000, msg,null);

			response.getWriter().print(  JSON.toJSONString( objectApiResult ) );
				return false;
		}




}
